<?php
namespace app\api\controller;
use think\Input;
use think\Controller;
use app\admin\model\Networks;
use app\admin\model\Clouds;
use app\admin\model\Messages;
use app\admin\model\Users;
use app\admin\model\Takes;
use app\common\controller\Base;
class Take extends Base{
    public function _initialize(){
        parent::_initialize();
        $this->heade=lang('Contract Number/User Name/Company Name/Line Name/Local Access/Peer-to-Peer Connection Input/Bandwidth (Mbps)/Purchase Time (Month)');
        $this->heades = explode("/", $this->heade);
        $this->Network = new Networks;
        $this->Takes = new Takes;
    }
    public function index(){
        $ws['status'] = 1;
        $takes = db('takes')->where($ws)->select();
        if($takes){
            foreach($takes as $take){
                $mo = month_dill($take['create_time'],time());
                if($mo%$take['month'] == 0 || date('Y-m',$take['create_time']) == date('Y-m',time())){ //每月
                    if($take['type'] == 1){
                        $this->exportUsers($take); 
                    }else{
                        $this->exportNetwords($take); 
                    }
                }
            }
            
        }
    }
    /*導出用户*/
    private function exportUsers($take){
        $map = [];
        if(!Users::isAdmin($take['user_id']) && !Users::isService($take['user_id']) && !Users::isChannel($take['user_id']) && !Users::isEngineer($take['user_id'])){
            $supIds = Users::getCustomerList($take['user_id']); //获取到签到管理员
            array_push($supIds, $take['user_id']);
            $map['sup_id'] = array('in',$supIds);
        }
        $users = db('users')->alias('u')
            ->join('auth_group g',"g.group_id=u.group_id")
            ->field('u.*,g.title')
            ->where($map)
            ->order('u.add_time desc')
            ->select();
        $username = Users::getUsername($take['user_id']);
        if($users){
            foreach($users as $k=>$user){
                $base[] = array(
                    'userid'=>$user['admin_id'],
                    'username'=>$user['username'],
                    'groupname'=>$user['title'],
                    'email'=>$user['email'],
                    'mobile'=>$user['tel'],
                    'telephone'=>$user['telephone'],
                    'company' => $user['company'],
                    'address'=>$user['address'],
                    'position'=>$user['position'],
                    'CreateTime' => date('Y-m-d H:i',$user['add_time']),
                    'status'=>($user['is_open'] == 1 ? lang('Normal') : lang('Disable')),
                );
            }
            $title = config('sys_name')." - ".lang('User information list');
            $heades = "User Id/User Name/Group Name/Email/Mobile/Telephone/Company/Address/Position/Create Time/status";
            $filename = $this->export('CloudFastUser'.$take['id'],explode("/", $heades),$base);
            $emails = [];
            if(is_email($take['email'])){
                $emails[] = $take['email'];
            }
            if(is_email($take['email2'])){
                $emails[] = $take['email2'];
            }
            if(count($emails) > 0){
                $result = send_email($emails,$title,lang('<h3>'.lang('Dear user%s, Hello!').'</h3><p>'.lang('For details of your route information, please download the attachment:').'</p><p>'.lang('email-footer').'</p>'),$filename);
            }
        }
    }
    /*導出發送路綫*/
    private function exportNetwords($take){
        $map['m.is_delete'] = 0;
        $map['m.is_sn'] = 1;
        $username = Users::getUsername($take['user_id']);
        if(Users::isCustomer($take['user_id'])){  //是客户
            $map['m.user_id'] = $take['user_id'];
        }elseif(!Users::isAdmin($take['user_id']) && !Users::isService($take['user_id']) && !Users::isChannel($take['user_id']) && !Users::isEngineer($take['user_id'])){
            $supIds = Users::getCustomerList($take['user_id']); //获取到签到管理员
            array_push($supIds, $take['user_id']);
            $map['u.sup_id'] = array('in',$supIds);
        }
        $networks = $this->Network->alias('m')
                ->join('users u',"u.admin_id = m.user_id")
                ->field('m.*,m.appro_time as approtime,m.local_cloud_id as locallabel,m.status as statuslabel,u.username,u.company,m.type as typelabel,m.endcloudid as endclou')
                ->where($map)->order('m.update_time desc,m.id desc')->select();
        if($networks){
            $base = [];
            foreach($networks as $k=>$vo){
                $vo['is_out'] = 0;
                if($vo['status'] == 2 && strtotime($vo['enddate']) < strtotime(date('Y-m-d',time()))){ //过期
                    $vo['is_out'] = 1;
                    $vo['statuslabel'] = lang('OutTime');
                }
                
                $vo['item'] = $k+1;
                $base[] = array(
                    'sn'=>$vo['sn'],
                    'username'=>$vo['username'],
                    'company'=>$vo['company'],
                    'name'=>$vo['name'],
                    'locallabel'=>$vo['locallabel'],
                    'endlabel'=>$vo['endclou'],
                    'broadband'=>$vo['broadband'].lang('Mbs'),
                    'daylength'=>$vo['daylength'].lang('Months'),
                );
                $data[] = $vo;
            }
            $title = config('sys_name')." - ".$this->Takes->getTypeAttr($take['type']);
            $filename = $this->export('CloudFast',$this->heades,$base);
            $emails = [];
            if(is_email($take['email'])){
                $emails[] = $take['email'];
            }
            if(is_email($take['email2'])){
                $emails[] = $take['email2'];
            }
            if(count($emails) > 0){
                $result = send_email($emails,$title,lang('<h3>'.lang('Dear user%s, Hello!',[$username]).'</h3><p>'.lang('For details of your route information, please download the attachment:').'</p><p>'.lang('email-footer').'</p>'),$filename);
            }
            
        }
    }
    
    /*導出數據*/
    public function export($fileName, $headArr, $data){
        header("Content-type: text/html; charset=utf-8");
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
        import("Excel.PHPExcel",PLUGIN_PATH);
        import("Excel.PHPExcel.Writer.Excel2007",PLUGIN_PATH);
        import("Excel.PHPExcel.IOFactory",PLUGIN_PATH);
        $date = date("Y-m-d", time());
        $fileName = iconv("utf-8", "gb2312", $fileName);
        if (empty($fileName)) {
            $fileName = date("Y-m-dHis", time()).".xls";
        }else{
            $fileName .= "-{$date}.xlsx";
        }
        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();
        //设置表头
        $key = ord("A");
        $headIndex = 1;
        $objActSheet = $objPHPExcel->getActiveSheet();
        if(!empty($baseHead) && is_array($baseHead)){
            foreach ($baseHead as $k=>$v) {
                $colum = chr($key).$headIndex;
                if($k>1){
                    $cellcolum = chr($key+$k-1).$headIndex;
                    $objActSheet->mergeCells($colum.':'.$cellcolum);
                }
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum, $v);
                $k = $k==0?1:$k;
                $key += $k;
            }
            $headIndex = 2;
        }
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . $headIndex, $v);
            if($colum=='A' || $colum=='I' || $colum=='J'){
                $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($colum)->setWidth(15);
            }else{
                $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($colum)->setWidth(25);
            }
            
            $key += 1;
        }
        $column = $headIndex+1;
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->getActiveSheet()->setTitle("Cloud Fast"); 
        $objPHPExcel->setActiveSheetIndex(0);
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $filePath = 'excel/'.date('Ymd',time())."/";
        $Path = $filePath;
        if(!is_dir($Path)){
            make_dir($Path);
        }
        if(file_exists($Path.$fileName)){
            unlink(ROOT_WWW."/public/".$Path.$fileName);
        }
        $objWriter->save($Path.$fileName); //文件通过浏览器下载
        $fileName = iconv("gb2312", "utf-8", $fileName);
        return $Path.$fileName;
    }
}